package com.sun.showcase.biz.sms;

import java.util.Hashtable;
import java.util.Random;
import org.springframework.stereotype.Component;
import com.sun.showcase.utils.ExecuteResult;

@Component
public class SmsComponent {

	private static Hashtable<String, Sms> smses = new Hashtable<String, Sms>();//短信存储
	
	//发送
	public synchronized void send(String phone,String type) {
		
		long time = System.currentTimeMillis();//时间戳
		
		String key = key(phone,type);
		
		Sms sms = smses.get(key);
		
		if(null!=sms && (time-sms.getTime())<1000*60*10) 
			return;
		
		
		if(null!=sms) 
			smses.remove(key);
		
		String code = random();//随机数
		
		SmsClient.send(phone, code,type);
		
		sms = new Sms(phone,type,time,code);
		
		smses.put(key, sms);
		
	}
	
	//验证
	public ExecuteResult<String> validate(String phone,String type,String code) {
		
		ExecuteResult<String> result = new ExecuteResult<String>();		
		/*if("888".equals(code)) {
			result.setSuccessMessage("验证成功！");
			
			return result;
		}*/
		long time = System.currentTimeMillis();//时间戳
		
		String key = key(phone,type);
		
		Sms sms = SmsComponent.smses.get(key);
		
		if(null==sms) {
			
			
			result.addErrorMessage("无此手机验证码！");
			
			return result;
		}
		
		if(time-sms.getTime()>1000*60*10) {
			
			result.addErrorMessage("短信验证超时！");
			
			return result;
		}
		
		if(!sms.getCode().equals(code)) {
			
			result.addErrorMessage("验证码错误！");
			
			return result;
		}
		
		
		SmsComponent.smses.remove(key);//移除
		
		result.setSuccessMessage("验证成功！");
		
		return result;
	}
	
	
	
	//清除
	public void clear() {
		
		SmsComponent.smses.clear();
	}
	
	private String key(String phone,String type) {
		
		return phone+"-"+type;
	}
	
	
	//随机数
	private String random() {
		
		Random r  =new Random();
		
		StringBuffer sb = new StringBuffer();
		
		for(int i=0;i<4;i++) {
			
			sb.append(r.nextInt(9)%(9-1+1)+1);
		}
		
		return sb.toString();
	}

    class Sms{
    	
    	private String phone;
    	
    	private String type;
    	
    	private long time;
    	
    	private String code;
    	
    	public Sms(String phone,String type,long time,String code) {
    		
    		this.phone = phone;
    		
    		this.type = type;
    		
    		this.time = time;
    		
    		this.code = code;
    	}

		public String getPhone() {
			return phone;
		}

		public void setPhone(String phone) {
			this.phone = phone;
		}

		public String getType() {
			return type;
		}

		public void setType(String type) {
			this.type = type;
		}

		public long getTime() {
			return time;
		}

		public void setTime(long time) {
			this.time = time;
		}

		public String getCode() {
			return code;
		}

		public void setCode(String code) {
			this.code = code;
		}
    	
    	
    }
}
